//
//  MVCViewController.m
//  MV_C_P_VM
//
//  Created by Willian on 2021/4/29.
//

#import "MVPViewController.h"

#import "CommonHeader.h"

#import "MVPLoginView.h"
#import "MVPLoginModel.h"
#import "Presenter.h"

@interface MVPViewController () <UITextFieldDelegate, PresenterDelegate>

@property (nonatomic, strong) MVPLoginView *loginView;
@property (nonatomic, strong) MVPLoginModel *loginModel;
@property (nonatomic, strong) Presenter *presenter;

@end

@implementation MVPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //模型
    self.loginModel = [[MVPLoginModel alloc] init];
    
    //视图
    self.loginView = [[MVPLoginView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, 400)];
    self.loginView.usernameTextField.delegate = self;
    self.loginView.passwordTextField.delegate = self;
    [self.view addSubview:self.loginView];
    
    [self.loginView.loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    //按钮先不可点击
    self.loginView.usernameTextField.backgroundColor = WhiteBgColor;
    self.loginView.passwordTextField.backgroundColor = WhiteBgColor;
    self.loginView.loginButton.enabled = NO;
    
    //实例化Presenter对象
    self.presenter = [Presenter new];
    self.presenter.delegate = self;
}

- (void)loginButtonClick{
    NSLog(@"登录按钮点击了");
}

#pragma mark - UITextFieldDelegate   这里是View -> model
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string{
    //OC中 字符串的拼接
    if (textField == self.loginView.usernameTextField) {
        NSString *userName = [textField.text stringByReplacingCharactersInRange:range withString:string];
        //保存用户名
        self.loginModel.userName = userName;
        
        //model -> View
        [self.presenter updateUsername:userName];
    } else {
        NSString *password = [textField.text stringByReplacingCharactersInRange:range withString:string];
        //保存密码
        self.loginModel.password = password;
        
        //model -> View
        [self.presenter updatePassword:[textField.text stringByReplacingCharactersInRange:range withString:string]];
    }
    return YES;
}

#pragma mark - PresenterDelegate  这里是 model -> View
- (void)updateUsernameBgColor:(UIColor *)color{
    self.loginView.usernameTextField.backgroundColor = color;
}
- (void)updatePasswordBgColor:(UIColor *)color{
    self.loginView.passwordTextField.backgroundColor = color;
}
- (void)updateLoginEnabled:(BOOL)enabled{
    self.loginView.loginButton.enabled = enabled;
}


@end

